<!--
 * @Author: your name
 * @Date: 2021-03-15 20:53:56
 * @LastEditTime: 2021-03-15 20:56:17
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edi
 * @FilePath: \study\js\面试题\数组计算.html
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <h1>
      给Array增加一个原型方法，返回数组中和为S的两个数，如果存在多组，返回乘积最小的组合
    </h1>
    <script>
      Array.prototype.calr = function (sum) {
        let arrs = this;
        let sums = [];
        let result = null;
        let curI = null;
        let curJ = null;
        for (let i = 0; i < arrs.length; i++) {
          for (let j = i; j < arrs.length; j++) {
            if (arrs[i] + arrs[j] == sum) {
              sums.push({
                i: arrs[i],
                j: arrs[j],
              });
            }
          }
        }
        console.log(`加和为 ${sum} `, sums);
        if (sums.length >= 1) {
          sums.forEach(function (item) {
            console.log(item);
            if (item.i * item.j < result || !result) {
              result = item.i * item.j;
              curI = item.i;
              curJ = item.j;
            }
          });
          return [curI, curJ];
        } else {
          return [];
        }
      };

      Array.prototype.calr1 = function (sum) {
        let arrs = this;
        let sums = [];
        let result = null;
        let curI = null;
        let curJ = null;
        for (let i = 0; i < arrs.length; i++) {
          for (let j = i; j < arrs.length; j++) {
            if (arrs[i] + arrs[j] == sum) {
              sums.push({
                i: arrs[i],
                j: arrs[j],
              });
              if (arrs[i] * arrs[j] < result || !result) {
                result = arrs[i] * arrs[j];
                curI = arrs[i];
                curJ = arrs[j];
              }
            }
          }
        }
        console.log(`加和为 ${sum} `, sums);
        if (sums.length >= 1) {
          return [curI, curJ];
        } else {
          return [];
        }
      };
      let arr = [1, 2, 3, 4, 5];
      //   let rr = arr.calr(5);
      let rr = arr.calr1(5);
      console.log(rr);
    </script>
  </body>
</html>
